<!--
  - Copyright (c) 2019.  武汉中科图灵科技有限公司
  - Date :  2019/1/5
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.6.2
  -->

<template>
  <div class="login-container login-turing-container">
    <!--登录模块-->
    <div class="index-login-section">
      <div class="system-title-warp">
        <div class="system-title-label">
          智慧消防云平台
        </div>
        <div class="system-title-asside">
          Smart fire cloud platform
        </div>
      </div>

      <div class="form-border-warp">
        <div
          class="warp-border-corner"
          style="left: -6px;top: -6px;transform: rotate(180deg);"
        />
        <div
          class="warp-border-corner"
          style="right: -5px;top: -7px;transform: rotate(-90deg);"
        />
        <div
          class="warp-border-corner"
          style="left: -5px;bottom: -7px;transform: rotate(90deg);"
        />
        <div class="warp-border-corner" style="right: -6px;bottom: -6px;" />

        <div class="login-title">
          用户登录
        </div>
        <!-- 登录 -->
        <el-form
          class="login-form"
          autoComplete="on"
          :model="loginForm"
          :rules="loginRules"
          ref="loginForm"
          label-position="left"
          v-if="login"
          :key="1"
          @keydown.enter.native="handleLogin"
        >
          <el-form-item prop="username" class="username">
            <el-input
              name="username"
              type="text"
              v-model.trim="loginForm.username"
              autoComplete="on"
              placeholder="用户名"
              icon="el-icon-search"
            >
              <img
                slot="prefix"
                class="input-icon"
                src="../../assets/login-bg_images/user.svg"
              />
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              name="password"
              :type="passwordType"
              v-model.trim="loginForm.password"
              placeholder="密码"
            >
              <img
                slot="prefix"
                class="input-icon"
                src="../../assets/login-bg_images/pwd.svg"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="code-box">
            <el-input
              name="code"
              type="text"
              class="validate-img"
              v-model.trim="loginForm.code"
              placeholder="验证码"
            >
              <img
                style="margin-top: 9px;"
                slot="prefix"
                class="input-icon"
                src="../../assets/login-bg_images/code.svg"
              />
              <template slot="append">
                <div class="code" @click="changeImgcode">
                  <img :src="validateimg" alt="验证码" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-button
            type="primary"
            class="login-bottom-submit"
            :loading="loading"
            @click="handleLogin"
            id="submitbtn"
            >登录</el-button
          >
          <div class="footer">
            <div class="footer-box">
              <span>
                <el-checkbox class="checkbox" v-model="checked"
                  >记住我</el-checkbox
                >
              </span>
              <!-- @click="forgetPassword" -->
              <span class="forget">忘记密码 ？</span>
            </div>
          </div>
          <!-- 特殊图形 -->
        </el-form>

        <!-- 忘记密码 -->
        <el-form
          class="login-form"
          :model="forgetForm"
          :rules="forgetRules"
          ref="forgetForm"
          label-position="left"
          v-else
          :key="2"
          @submit.native.prevent
        >
          <h3>忘记密码</h3>
          <el-form-item class="username" prop="fusername">
            <el-input
              type="text"
              v-model.trim="forgetForm.fusername"
              placeholder="用户名"
            ></el-input>
          </el-form-item>
          <el-form-item class="code-box code-num" prop="phonecode">
            <el-input
              type="text"
              v-model.trim="forgetForm.phonecode"
              maxlength="10"
              placeholder="验证码"
            ></el-input>
            <el-button
              class="code-btn"
              type="text"
              @click="sendPhonecode"
              :disabled="isOvertime"
              >{{ phoneword }}</el-button
            >
          </el-form-item>
          <el-form-item prop="newpassword">
            <el-input
              name="newpassword"
              type="password"
              v-model.trim="forgetForm.newpassword"
              placeholder="新密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="confirmpassword">
            <el-input
              name="confirmpassword"
              type="password"
              v-model.trim="forgetForm.confirmpassword"
              placeholder="确认新密码"
            ></el-input>
          </el-form-item>
          <el-button
            type="primary"
            class="login-bottom-submit"
            @click.native.prevent="handleForget"
            native-type="submit"
            >确定</el-button
          >
          <div class="backlogin">
            <el-button type="text" @click="backlogin">
              <i class="el-icon-back"></i>返回登录</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
    <!-- 底部信息 -->
    <!-- <div class="index-footer">
      <div class="index-footer-wrap">
        <div class="index-footer-wrapbottom">
          <br />
          Copyright &copy; 武汉中科图灵科技有限公司, All Rights Reserved.
        </div>
      </div>
    </div> -->
  </div>
</template>
<script>
import { randomn } from "@/utils";
import imglogo from "@/assets/login-bg_images/login-r.png";
import Cookies from "js-cookie";
import { isvalidPhone } from "@/utils/validate";
var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入手机号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的手机号码"));
  } else {
    callback();
  }
};
export default {
  name: "login",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };
    const confirmPw = (rule, value, callback) => {
      if (value !== this.forgetForm.newpassword) {
        callback(new Error("密码不一致"));
      } else {
        callback();
      }
    };
    return {
      checked: false,
      imglogo,
      phoneword: "获取验证码",
      isOvertime: false,
      labelPosition: "top",
      validateimg: "/api/admin/image/getCode",
      login: true,
      sizeForm: {
        type: ""
      },
      forgetForm: {
        fusername: "",
        phonecode: "",
        newpassword: "",
        confirmpassword: ""
      },
      forgetRules: {
        fusername: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur"
          }
        ],
        phonecode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          }
        ],
        newpassword: [
          {
            required: true,
            message: "新密码不能为空",
            trigger: "blur"
          },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur"
          }
        ],
        confirmpassword: [
          {
            required: true,
            message: "密码不一致",
            trigger: "blur"
          },
          {
            required: true,
            trigger: "blur",
            validator: confirmPw
          }
        ]
      },
      loginForm: {
        username: localStorage.getItem("logined") || "",
        password: "",
        code: "",
        image: ""
      },
      loginRules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePass
          }
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          },
          {
            min: 4,
            max: 4,
            message: "验证码不正确",
            trigger: "blur"
          }
        ]
      },
      passwordType: "password",
      loading: false,
      showDialog: false
    };
  },
  mounted() {
    if (localStorage.getItem("logined") !== null) {
      this.checked = true;
    }
  },
  methods: {
    getRandom() {
      return Math.random()
        .toString(36)
        .substr(2);
    },
    changeImgcode() {
      if (this.validateimg.indexOf("?") > 0) {
        this.validateimg =
          this.validateimg.split("?")[0] + "?" + this.getRandom();
      } else {
        this.validateimg = this.validateimg + "?" + this.getRandom();
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let self = this;
          this.loginForm.image = Cookies.get("image");
          self.$store
            .dispatch("LoginByUsername", self.loginForm)
            .then(() => {
              self.$router.push({
                path: "/"
              });
              // 如果勾选了记住
              if (self.checked) {
                localStorage.setItem("logined", self.loginForm.username);
              } else {
                if (
                  self.loginForm.username === localStorage.getItem("logined")
                ) {
                  localStorage.removeItem("logined");
                }
              }
            })
            .catch(() => {
              self.loading = false;
              self.changeImgcode();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    apiSendcode() {
      let self = this;
      this.loading = true;
      this.$axios
        .get("/api/admin/valicode/sms", {
          params: { username: self.forgetForm.fusername }
        })
        .then(function(response) {
          self.loading = false;
          let res = response.data;
          if (res.status === 200) {
            self.$notify({
              title: "成功",
              message: "验证码已发送到" + res.data,
              type: "success",
              position: "bottom-right"
            });

            self.showcodetime();
          } else {
            self.$notify({
              title: "警告",
              message: "用户名不存在！",
              type: "warning",
              position: "bottom-right"
            });
          }
        })
        .catch(function(error) {
          self.loading = false;
          self.$message({
            message: error.response.data.message,
            type: "warning"
          });
        });
    },
    showcodetime() {
      if (this.isOvertime) {
        return false;
      }
      let that = this,
        time = 60;
      var sendTimer = setInterval(function() {
        that.isOvertime = true;
        time--;
        that.phoneword = "已发送(" + time + "s)";
        if (time < 0) {
          that.isOvertime = false;
          clearInterval(sendTimer);
          that.phoneword = "获取验证码";
        }
      }, 1000);
    },
    sendPhonecode() {
      this.apiSendcode();
    },
    handleForget() {
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          let self = this;

          this.$axios
            .post(
              "/api/admin/user/updatepwd",
              this.$qs.stringify({
                username: self.forgetForm.fusername,
                code: self.forgetForm.phonecode,
                pwd: window.btoa(
                  window.btoa(self.forgetForm.confirmpassword) + randomn(7)
                )
              })
            )
            .then(function(response) {
              let res = response.data;
              if (res.status === 200) {
                self.$message({
                  showClose: true,
                  message: "修改密码成功",
                  type: "success"
                });
                setTimeout(() => {
                  location.reload();
                }, 300);
              } else {
                self.$message({
                  showClose: true,
                  message: res.message,
                  type: "warning"
                });
              }
            })
            .catch(function(error) {
              self.loading = false;
              self.$message({
                message: error.response.data.message,
                type: "warning"
              });
            });
        } else {
          return false;
        }
      });
    },
    afterQRScan() {
      // const hash = window.location.hash.slice(1)
      // const hashObj = getQueryObject(hash)
      // const originUrl = window.location.origin
      // history.replaceState({}, '', originUrl)
      // const codeMap = {
      //   wechat: 'code',
      //   tencent: 'code'
      // }
      // const codeName = hashObj[codeMap[this.auth_type]]
      // if (!codeName) {
      //   alert('第三方登录失败')
      // } else {
      //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
      //     this.$router.push({ path: '/' })
      //   })
      // }
    },
    forgetPassword() {
      //this.$refs["loginForm"].resetFields();
      //this.forgetForm.phonecode = "";
      //this.$refs["forgetForm"].resetFields();
      this.login = false;
      this.forgetForm.fusername = JSON.parse(
        JSON.stringify(this.loginForm.username)
      );
    },
    backlogin() {
      this.$refs["forgetForm"].resetFields();
      this.login = true;
    },
    submit() {}
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
    //this.getValidateImg()
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg: #2d3a4b;
$light_gray: #000;

/* reset element-ui css */
.login-container {
  background-image: url(../../../src/assets/login-bg_images/login-bg.png);
  background-size: cover;
  background-position: 50%;
  .el-form-item {
    height: 45px;
    width: 416px;
    margin: 20px auto;
  }
  .el-form-item.is-required .el-form-item__label:before {
    content: "";
  }
  .el-input--medium .el-input__inner {
    height: 45px;
    line-height: 45px;
    border: solid 2px #0ba1f8;
    padding-left: 53px;
  }
  .el-input__inner {
    background: reba(255, 255, 255, 0.4);
    font-size: 20px;
    letter-spacing: 2px;
    color: #ffffff;
    border-radius: 0;
  }
  .el-input__prefix {
    line-height: 58px;
    left: 20px;
  }

  .validate-img {
    /deep/ .el-input-group__append {
      padding: 0 85px;
      background: #fff;
      border: 0;
    }
  }
  .code-btn.is-disabled {
    span {
      color: #c0c4cc;
    }
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  min-height: 100vh;
  @include relative;
  display: flex;
  align-items: center;

  .index-login-section {
    width: 1300px;
    height: 480px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;

    .system-title-warp {
      padding: 183px 4px 0;
      text-align: center;

      .system-title-label {
        font-size: 55px;
        color: #eff0f1;
        font-weight: bold;
        white-space: nowrap;
        color: #eff0f1;
        letter-spacing: 2px;
        font-family: "Audiowide";
        text-shadow: 0 0 8px #0a4ebc, 0 0 5px #0a4ebc, 0 0 8px #0a4ebc,
          0 0 10px #0a4ebc, 0 0 15px #0a4ebc, 0 0 40px #0a4ebc, 0 0 50px #0a4ebc,
          0 0 75px #0a4ebc;
      }

      .system-title-asside {
        margin-top: 20px;
        font-size: 22px;
        line-height: 14px;
        letter-spacing: 0px;
        color: #51a4ff;
      }
    }

    .login-bottom-submit {
      width: 416px;
      height: 46px;
      line-height: 28px;
      display: flex;
      justify-content: center;
      margin: 30px auto 20px auto;
      background-color: #4aabfe;
      font-size: 20px;
      font-weight: bold;
      letter-spacing: 4px;
      color: #ffffff;
    }
  }

  .login-title {
    margin-top: 54px;
    font-size: 26px;
    line-height: 12px;
    letter-spacing: 5px;
    color: #ffffff;
    text-align: center;
  }

  .form-border-warp {
    position: relative;
    width: fit-content;
    height: auto;
    border: 1px solid #0063ba;
    background: rgba(4, 89, 168, 0.5);

    .warp-border-corner {
      position: absolute;
      background: url("../../assets/login-bg_images/border-corner.png")
        no-repeat;
      background-size: cover;
      position: absolute;
      width: 47.5px;
      height: 49px;
    }
  }

  .login-form {
    width: 661px;
    height: 100%;
    padding: 1px 35px 15px;
    position: relative;

    .input-icon {
      width: 18px;
      height: auto;
      vertical-align: middle;
    }

    h3 {
      font-size: 31px;
      text-align: left;
      margin-left: 10px;
    }
    .username {
      margin-top: 30px;
    }

    .checkbox {
      color: #fff;
    }
    .footer {
      width: 348px;
      margin: 0 auto;
    }
    .forget {
      display: inline-block;
      padding-left: 10px;
      line-height: 19px;
      font-size: 14px;
      color: #fff;
      cursor: pointer;
    }
    .footer-box {
      display: flex;
      justify-content: space-between;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
  .code-box {
    position: relative;

    /deep/ .el-input__inner {
      width: 220px;
    }
    .code {
      position: absolute;
      top: 0;
      right: 0;
      background-color: #eee;
      width: 170px;
      height: 36px;
      img {
        height: 36px;
        width: 100%;
        border: solid 2px #0ba1f8;
      }
    }
  }
  .code-num {
    position: relative;
    .code-btn {
      width: 100px;
      height: 36px;
      border: solid 2px #0ba1f8;
      position: absolute;
    }
  }
  .backlogin {
    text-align: center;
    margin-top: 10px;
  }
}
.index-footer {
  position: absolute;
  bottom: 60px;
  width: 100%;
  .index-footer-wrap {
    max-width: 1200px;
    margin: 0 auto;
    .index-footer-wrapbottom {
      text-align: center;
      color: rgba(216, 216, 216, 0.5);
      font-size: 16px;
      line-height: 22px;
      .class-icon-show {
        font-size: 30px;
        cursor: pointer;
      }
    }
  }
}
</style>
